/*
 * @Author: Leander 
 * @Date: 2019-03-12 17:14:47 
 * @Last Modified by: Leander
 * @Last Modified time: 2019-03-14 14:55:41
 */
//导入模块
import axios from 'axios'
import router from '@/router'
import { Message } from 'element-ui'
import { apiapphome } from './env'
import { tools_uri, tools_verify } from '@/common/tools'
var sha1 = require('sha1');
var md5 = require('md5');

function _object(list, values) {
  //获取当前时间戳
  let timestamp = new Date().getTime()
  let result = {
    // 'timestamp': timestamp,
    'packey': '26d1b5a3346441ba839a68e0b7bb0284',
    'security_code': 'I8feVXtTO0mv42QB9omOjvV9JyunNrZb',
    'data_type': 'json',
    'data_sign': ''
  }
  for (let i = 0; i < list.length; i++) {
    if (values) {
      result[list[i]] = values[i]
    } else {
      result[list[i][0]] = list[i][1]
    }
  }
  let a = JSON.stringify(result)
  a = a + '3hd*RrMbocrk~==7hGyfpbEZwlEA2nWt]um(eg1.nqM~3vikNh8)T6Lxld5bCP#R'
  let b = sha1(md5(sha1(md5(a)))).substr(4, 32);
  result["data_sign"] = b
  return result;
}

function _arrval(params) {
  let keyarr = [],
    valuearr = []
  for (let key in params) {
    let objinner = params[key]
    for (let k in objinner) {
      if (tools_verify.isObject(objinner[k])) {
        for (let j in objinner[k]) {
          keyarr.push(`${k}[${j}]`)
          valuearr.push(objinner[k][j])
        }
      } else {
        keyarr.push(`${k}`)
        valuearr.push(objinner[k])
      }
    }
  }
  return {
    keyarr,
    valuearr,
  }
}



export default function fetch(options) {

  return new Promise((resolve, reject) => {

    //处理请求接口
    switch (options.baseURL) {
      case 0:
        options.baseURL = '';
        break;
      default:
        options.baseURL = apiapphome;
        break;
    }
    axios({
      method: "POST",
      headers: {
        'X-Requested-With': 'XMLHttpRequest',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8;',
      },
      url: `${options.baseURL}${options.url}`,
      data: _object(_arrval(options.params).keyarr, _arrval(options.params).valuearr),
      //使用post方法传参
      // data: options.params.data,
      //使用get方法传参
      // params: options.params.data,
      transformRequest: [function (data, headers) {
        return tools_uri.jointUrl(data)
			}],
      //withCredentials: false, // 允许携带cookie
    }).then(({ data: { code, code_msg, code_user_msg, result, status, type } }) => {
      if (status === true) {
        resolve(result)
        return false
      } else {
        Message.error('操作失败！错误原因 ' + code_user_msg)
        reject(code_user_msg)
      }

    }).catch(error => {
      //请求失败时,根据业务判断状态
      if (error.response) {
        let resError = error.response
        let resCode = resError.status
        let resMsg = error.message

        Message.error('操作失败！错误原因 ' + resMsg)
        reject({ code: resCode, msg: resMsg })
      }

    })

  })
}
